package cn.pxxy.controller;

import cn.pxxy.exception.LoginFailureException;
import cn.pxxy.util.CpachaUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/vcode")
public class VcodeController {
    private static final CpachaUtil cap = new CpachaUtil();

    // 初次进入页面  用mvc
    @RequestMapping("/login.html")
    public String loginHtml(HttpServletRequest request, HttpSession session) {
        String code = cap.generatorVCode();
        session.setAttribute("code", code);
        request.setAttribute("codeImage", cap.generatorVCodeImage(code, true));
        return "/login";
    }

    // 刷新验证码  用 ajax ,js 获取 图片二进制数据
    @RequestMapping("/flush-image")
    public ResponseEntity<byte[]> flushImage(HttpSession session) throws IOException {
        String code = cap.generatorVCode();
        session.setAttribute("code", code);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(cap.generatorRotateVCodeImage(code,true),"jpeg",out);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.OK);
    }

    // 真实 登录
    @RequestMapping("/login-with-nai-tang")
    public String loginWithNaiTang(String username , String password ,String code, HttpSession session) {
        if (!code.equals(session.getAttribute("code"))) {
            throw new LoginFailureException("验证码错误","尝试刷新验证码");
        }
        // 账号密码校验
        return  "/main";
    }
}
